import { loginAPI, getUserProfile, getUserPhotoAPI } from '@/api'
import { getToken, setToken, removeToken } from '@/utils/auth'
// import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    userInfo: {}, // 用户信息对象
    token: getToken()
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token // vuex存一份
    setToken(token) // 本地存一份
  },
  REMOVE_TOKEN: (state) => {
    state.token = ''
    removeToken()
  },
  // 设置用户信息
  SET_USER: (state, value) => {
    state.userInfo = value
  },
  // 删除用户信息
  REMOVE_USER: (state) => {
    state.userInfo = {}
  }
}

const actions = {
  async loginActions({ commit }, data) {
    const result = await loginAPI(data)
    commit('SET_TOKEN', result)
    return result // 结果返回给调用出
  },
  async getUserInfoActions({ commit }) {
    const result = await getUserProfile()
    const baseList = await getUserPhotoAPI(result.userId)
    // 调用mutations的用户信息
    // 合并对象
    commit('SET_USER', { ...result, ...baseList })
    return result
  },
  // 封装退出登录逻辑
  logoutActions({ commit }) {
    commit('REMOVE_TOKEN')
    commit('REMOVE_USER')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

